package com.xhwl.centiotdata.suppliersystem.haikangyunmou;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.centiotdata.pojo.constant.HaiKangYunMouConstant;
import com.xhwl.centiotdata.pojo.dto.haikangyunmou.*;
import com.xhwl.centiotdata.pojo.dto.pedestrian.PedestrianIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.pojo.enums.pedestrian.PedestrianMethodEnum;
import com.xhwl.centiotdata.service.cent.IAccountCentService;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.cent.IParameterConfigService;
import com.xhwl.centiotdata.service.cent.IResidentInfoService;
import com.xhwl.centiotdata.service.integrateconfig.PedestrianIntegrationConfig;
import com.xhwl.centiotdata.utils.RedisUtils;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.residence.ResidentInfoDTO;
import com.xhwl.common.enums.CategoryEnum;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.ParameterConfig;
import com.xhwl.common.pojo.cent.auth.AuthRelation;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.pojo.cent.residence.ResidentEstateRelation;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.criteria.ParamConfigCriteria;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.query.cent.device.ProductAccessQuery;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/03/ 10:15
 */
@Service
public class HaiKangYunMouUtils {

    private static final Logger log = LoggerFactory.getLogger(HaiKangYunMouUtils.class);

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private PedestrianIntegrationConfig integrationConfig;
    @Autowired
    public IDeviceCentService deviceCentService;
    @Autowired
    private IResidentInfoService residentInfoService;
    @Autowired
    private IAccountCentService accountCentService;
    @Autowired
    private IParameterConfigService configService;

    private static final Integer SUCCESS_CODE = 200;
    // 401为认证失败
    private static final Integer AUTHENTICATION_FAILED_CODE = 401;
    private static final Integer INVALID_CONSUMER_ID_CODE = 514002;

    /**
     * 创建消费者
     * @param config
     * @return
     */
    public String getConsumerId(PedestrianIntegrationConfigDTO config) {
        Integer projectId = config.getProjectId();
        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);

        String consumerIdKey = HaiKangYunMouConstant.CREATE_CONSUMER_ID + projectId;
        String consumerId;
        Object obj = redisUtils.get(consumerIdKey);
        if (obj == null) {
            Map<String, Object> map = new HashMap<>();
            map.put(HaiKangYunMouConstant.CONSUMER_NAME, projectId);
            HaiKangYunMouJson consumerResp = doReq(HaiKangYunMouConstant.CREATE_MQ_CONSUMER,
                    map, Method.POST, haiKangYunMouConfig, null);
            if (SUCCESS_CODE.equals(consumerResp.getCode())) {
                JSONObject data = (JSONObject) consumerResp.getData();
                consumerId = data.getString(HaiKangYunMouConstant.CONSUMER_ID);
                redisUtils.setWithMinute(consumerIdKey, consumerId, 5);
            } else {
                log.error("HaiKangYunMou getConsumerId exception, projectId:{}", projectId);
                throw new BusinessException();
            }
        } else {
            consumerId = (String) obj;
        }
        if (StringUtils.isEmpty(consumerId)) {
            throw new BusinessException("海康云眸创建消费者id异常");
        }
        return consumerId;
    }

    /**
     * 获取消费消息:30秒内必须再次调用拉取消息接口，否则将断开与消息通道的连接，因此拉取间隔需要在30秒以内，否则每次拉到的消息是空的
     * @param config
     * @param consumerId
     * @return
     */
    public List<MQConsumerMessagesDTO> getMQMsg(PedestrianIntegrationConfigDTO config, String consumerId) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.CONSUMER_ID, consumerId);
        // 是否自动提交偏移量，默认false(手动提交)
        map.put(HaiKangYunMouConstant.AUTO_COMMIT, true);

        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        HaiKangYunMouJson msgResp = doReq(HaiKangYunMouConstant.CONSUMING_MESSAGES,
                map, Method.POST, haiKangYunMouConfig, "标准格式");

        // 正确的消费方式是，单线程内拉取一次消息，判断消息列表不为空，则提交一次偏移量，请注意：提交偏移量和消费消息必须使用同一consumerId
        return JSONObject.parseArray(JSON.toJSONString(msgResp.getData()), MQConsumerMessagesDTO.class);
    }

    /**
     * 手动提交偏移量
     * @param config
     * @param consumerId
     * @return
     */
    public void msgOffsets(PedestrianIntegrationConfigDTO config, String consumerId) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.CONSUMER_ID, consumerId);
        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        // 正确的消费方式是，单线程内拉取一次消息，判断消息列表不为空，则提交一次偏移量，请注意：提交偏移量和消费消息必须使用同一consumerId
        doReq(HaiKangYunMouConstant.SUBMIT_OFFSET, map, Method.POST, haiKangYunMouConfig, null);
    }

    /**
     * 查询社区下的设备列表
     * 中建梅溪湖: 63e6df4da08643279ec0ba942d9088ea
     * @param config
     * @param
     * @return
     */
    public List<HaiKangYunMouDevice> getDevices(PedestrianIntegrationConfigDTO config, String communityId) {
        List<HaiKangYunMouDevice> list = new ArrayList<>();
        Integer pageNo = 1;
        Integer pageSize = 1000;
        List<HaiKangYunMouDevice> devices = null;
        boolean hasNextPage = false;
        do {
            Map<String, Object> map = new HashMap<>();
            map.put(HaiKangYunMouConstant.COMMUNITY_ID, communityId);
            map.put(HaiKangYunMouConstant.PAGE_NO, pageNo);
            map.put(HaiKangYunMouConstant.PAGE_SIZE, pageSize);

            HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
            BeanUtils.copyProperties(config, haiKangYunMouConfig);
            HaiKangYunMouJson resp = doReq(HaiKangYunMouConstant.DEVICES,
                    map, Method.POST, haiKangYunMouConfig, null);

            JSONObject jsonObject = (JSONObject) resp.getData();
            hasNextPage = jsonObject.getBoolean(HaiKangYunMouConstant.HAS_NEXT_PAGE);
            String row = jsonObject.getString(HaiKangYunMouConstant.ROWS);
            // log.info("数据：{}", JSONObject.toJSONString(row));
            devices = JSONObject.parseArray(row, HaiKangYunMouDevice.class);
            if (CollectionUtils.isEmpty(devices)) {
                break;
            }
            list.addAll(devices);
            ++pageNo;
        } while (!CollectionUtils.isEmpty(devices) && hasNextPage);
        return list;
    }

    /**
     * 住户人员权限批量下发
     * @param config
     * @param communityId
     * @return
     */
    public void batchAuthorityIssued(PedestrianIntegrationConfigDTO config, String communityId,
                                           List<String> personIds, List<String> deviceIds) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.COMMUNITY_ID, communityId);
        // 操作类型， [0]-按住户人员列表下发权限
        map.put(HaiKangYunMouConstant.OPERATION_TYPE, 0);
        // 住户人员ID列表,当operationType=0时生效
        map.put(HaiKangYunMouConstant.PERSON_IDS, personIds);
        map.put(HaiKangYunMouConstant.DEVICE_IDS, deviceIds);
        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        log.info("权限批量下发获取的参数为{}",map);
        doReq(HaiKangYunMouConstant.BATCH_AUTHORITY_ISSUED,
                map, Method.POST, haiKangYunMouConfig, null);
    }

    /**
     * 人员权限删除
     * @param config
     * @param communityId
     * @return
     */
    public void authorityDelete(PedestrianIntegrationConfigDTO config, String communityId,
                                     String personId, String deviceId) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.COMMUNITY_ID, communityId);
        map.put(HaiKangYunMouConstant.PERSON_ID, personId);
        // [0]物业;[1]住户;
        map.put(HaiKangYunMouConstant.PERSON_TYPE, 1);
        map.put(HaiKangYunMouConstant.DEVICE_ID, deviceId);

        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        log.error("获取的参数为{}",map);
        doReq(HaiKangYunMouConstant.AUTHORITY_DELETE,
                map, Method.POST, haiKangYunMouConfig, null);
    }

    /**
     * 访客登记（预约）
     * @param config
     * @return reservationId 预约记录id
     */
    public String visitors(PedestrianIntegrationConfigDTO config, HaiKangYunMouVisitors visitors) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.PERSON_ID, visitors.getPersonId());
        // [0]物业;[1]住户;
        map.put(HaiKangYunMouConstant.PERSON_TYPE, visitors.getPersonType());
        map.put(HaiKangYunMouConstant.VISITOR_NAME, visitors.getVisitorName());
        map.put(HaiKangYunMouConstant.GENDER, visitors.getGender());
        map.put(HaiKangYunMouConstant.PHONE, visitors.getPhone());
        map.put(HaiKangYunMouConstant.ROOM_ID, visitors.getRoomId());
        map.put(HaiKangYunMouConstant.VISITOR_EFFECTIVE_TIME, visitors.getVisitorEffectiveTime());
        map.put(HaiKangYunMouConstant.VISITOR_LEAVE_TIME, visitors.getVisitorLeaveTime());
        map.put(HaiKangYunMouConstant.VISIT_REASON,visitors.getVisitReason());
        if (!org.springframework.util.StringUtils.isEmpty(visitors.getDeviceIds())) {
            map.put(HaiKangYunMouConstant.DEVICE_IDS, visitors.getDeviceIds());
        }
        log.info("获取的参数{}",map);
        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        HaiKangYunMouJson resp = doReq(HaiKangYunMouConstant.VISITORS,
                map, Method.POST, haiKangYunMouConfig, null);

        JSONObject data = (JSONObject) resp.getData();
        String reservationId = data.getString(HaiKangYunMouConstant.RESERVATION_ID);
        String visitorCode = data.getString(HaiKangYunMouConstant.VISITOR_CODE);
        // 把二维码信息存redis
        redisUtils.setWithMinute(HaiKangYunMouConstant.QR + reservationId, visitorCode, HaiKangYunMouConstant.THREE_DAYS);
        return visitorCode;
    }

    /**
     * 访客删除
     * @param config
     * @return
     */
    public void deleteVisitors(PedestrianIntegrationConfigDTO config, String reservationId) {
        redisUtils.remove(HaiKangYunMouConstant.QR + reservationId);

        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        String url = HaiKangYunMouConstant.DELETE_VISITORS + reservationId;
        doReq(url,null, Method.DELETE, haiKangYunMouConfig, null);
    }

    /**
     * 获取人员户室信息
     * @param config
     * @return
     */
    public String getRoomId(PedestrianIntegrationConfigDTO config, String personId, String communityId) {
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.PERSON_ID, personId);
        map.put(HaiKangYunMouConstant.COMMUNITY_ID, communityId);
        map.put(HaiKangYunMouConstant.PAGE_NO, 1);
        map.put(HaiKangYunMouConstant.PAGE_SIZE, 1);

        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        HaiKangYunMouJson resp = doReq(HaiKangYunMouConstant.ROOM_LIST,
                map, Method.GET, haiKangYunMouConfig, null);
        log.info("调用海康接口返回的数据为{}",resp.getData());
        JSONObject jsonObject = (JSONObject) resp.getData();
        String row = jsonObject.getString(HaiKangYunMouConstant.ROWS);
        String roomId = null;
        if (!StringUtils.isEmpty(row)){
            List<HaiKangYunMouRoom> roomList = JSONObject.parseArray(row, HaiKangYunMouRoom.class);
            if (!CollectionUtils.isEmpty(roomList)){
                HaiKangYunMouRoom room = roomList.get(0);
                roomId = room.getRoomId();
            }
        }
        List<DeviceProjSupplierCategory> deviceConfigList = deviceCentService.listProductAccess((short) 1, new ProductAccessQuery(config.getProjectId(), CategoryEnum.VISITOR_SYSTEM.getId()));
        JSONObject properties = deviceConfigList.get(0).getProperties();
        if (StringUtils.isEmpty(roomId)) {
            roomId = properties.getString("defaultRoomId");
            log.error("获取的roomId为{}",roomId);
            // throw new BusinessException("海康云眸获取人员户室信息失败");
        }
        log.error("获取的roomId为{}",roomId);
        return roomId;
    }

    public String getToken(Integer projectId, String ak, String sk) {
        String tokenKey = HaiKangYunMouConstant.TOKEN + projectId;
        String token;
        Object obj = redisUtils.get(tokenKey);
        if (obj == null) {
            do {
                token = setToken(projectId, ak, sk);
            } while (token != null);
        } else {
            token = (String) obj;
        }
        return token;
    }

    /**
     * （401执行）
     * key: HaiKangYunMouConstant.TOKEN + projectId
     * @param projectId
     * @param ak
     * @param sk
     * @return
     */
    public String setToken(Integer projectId, String ak, String sk) {
        String tokenKey = HaiKangYunMouConstant.TOKEN + projectId;
        try {
            String path = HaiKangYunMouConstant.HOST + HaiKangYunMouConstant.TOKEN_URL;
            String result = HttpUtil.createPost(path)
                    .form(HaiKangYunMouConstant.CLIENT_ID, ak)
                    .form(HaiKangYunMouConstant.CLIENT_SECRET, sk)
                    .form(HaiKangYunMouConstant.GRANT_TYPE, HaiKangYunMouConstant.CLIENT_CREDENTIALS)
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute()
                    .body();
            JSONObject resultObject = JSON.parseObject(result);
            String token = resultObject.getString(HaiKangYunMouConstant.ACCESS_TOKEN);
            Integer expires = resultObject.getInteger(HaiKangYunMouConstant.EXPIRES_IN);
            redisUtils.setWithSeconds(tokenKey, token, expires);
        } catch (Exception e) {
            log.error("HaiKangYunMou getAccessToken exception projectId:{}, msg:{}", projectId, e.getMessage());
            throw new BusinessException();
        }
        return (String) redisUtils.get(tokenKey);
    }


    public List<String> getCommunityIdByProjectId(Integer projectId) {
        PedestrianIntegrationConfigDTO config = getConfig(projectId);
        if (ObjectUtils.isEmpty(config)) {
            throw new RuntimeException("获取人行配置异常");
        }
        List<String> communityId = getCommunityId(config);
        if (org.springframework.util.StringUtils.isEmpty(communityId)) {
            throw new RuntimeException("获取社区id失败");
        }
        return communityId;
    }

    public List<String> getCommunityId(PedestrianIntegrationConfigDTO config) {
        Integer projectId = config.getProjectId();
        String orgIndexCode = config.getOrgIndexCode();
        String orgStr = JSONObject.toJSONString(orgIndexCode);
        Object obj = JSON.parse(orgStr);
        String objStr = obj.toString();
        List<HaiKangYunMouProject> list = JSONObject.parseArray(objStr, HaiKangYunMouProject.class);
        Map<Integer, List<String>> map = list.stream().collect(
                Collectors.groupingBy(HaiKangYunMouProject::getProjectId,Collectors.mapping(HaiKangYunMouProject::getCommunityId, Collectors.toList())));
        return map.get(projectId);
    }
    /**
     * 海康云眸获取默认的楼栋/单元/房间信息
     * @param  projectId
     * @return
     */
    public List<HaiKangYunMouProject> getDefaultYunMouConfigByProjectId(Integer projectId,Integer accountId) {
        PedestrianIntegrationConfigDTO config = getConfig(projectId);
        if (ObjectUtils.isEmpty(config)) {
            throw new RuntimeException("获取人行配置异常");
        }
        String orgIndexCode = config.getOrgIndexCode();
        String orgStr = JSONObject.toJSONString(orgIndexCode);
        Object obj = JSON.parse(orgStr);
        String objStr = obj.toString();
        List<HaiKangYunMouProject> list = JSONObject.parseArray(objStr, HaiKangYunMouProject.class);
        //获取人员区域
        List<String> communityIds = getCommunityId(projectId,accountId);
        if (CollectionUtils.isEmpty(communityIds)){
            return list;
        }else {
            return list.stream().filter(pro ->pro.getProjectId().equals(projectId) && communityIds.contains(pro.getCommunityId())).collect(Collectors.toList());
        }
//        HaiKangYunMouProject haiKangYunMouProject = list.stream().filter(s->s.getProjectId().equals(projectId)).findAny().orElse(null);
    }

    public static void main(String[] args) {
        String value = "92,91";
        List<String> projectIds = Arrays.stream(value.split(",")).collect(Collectors.toList());
        if (!projectIds.contains(String.valueOf(91))){
            System.out.println(false);
        }else {
            System.out.println(true);
        }
    }
    /**
     * 根据用户获取对应的社区ID
     * @param accountId
     * @return
     */
    public List<String> getCommunityId(Integer projectId ,Integer accountId){
        List<Integer>  areaIds = new ArrayList<>();
        List<String> communityIds = getCommunityIdByProjectId(projectId);
        if (Objects.isNull(accountId)){
            return communityIds;
        }
        try {
            ParamConfigCriteria criteria = new ParamConfigCriteria();
            String code = "PEDES_AREA_PROJECT_CONFIG";
            criteria.withBusinessType(BusinessType.PROJECT).withBuzId(projectId).withCode(code).withStatus(true);
            ParameterConfig parameterConfig = configService.findByCriteria(criteria);
            if(null != parameterConfig) {
                log.info("parameterConfig{}", JSON.toJSONString(parameterConfig));
                if (Objects.nonNull(parameterConfig) && Objects.nonNull(parameterConfig.getValue())) {
                    String value = parameterConfig.getValue();
                    List<String> projectIds = Arrays.stream(value.split(",")).collect(Collectors.toList());
                    if (!projectIds.contains(String.valueOf(projectId))){
                        return communityIds;
                    }else {
                        code = "PEDES_AREA_CONFIG";
                        criteria.withBusinessType(BusinessType.PROJECT).withBuzId(projectId).withCode(code).withStatus(true);
                        parameterConfig = configService.findByCriteria(criteria);
                        if(null != parameterConfig) {
                            log.info("parameterConfig{}", JSON.toJSONString(parameterConfig));
                            if (Objects.nonNull(parameterConfig) && Objects.nonNull(parameterConfig.getValue())) {
                                value = parameterConfig.getValue();
                                JSONObject jsonObject = JSON.parseObject(value);
                                //配置了区域和社区对应关系才获取区域ID
                                ResidentInfoDTO residentInfoDTO = new ResidentInfoDTO();
                                residentInfoDTO.setProjectId(projectId);
                                residentInfoDTO.setAccountId(accountId);
                                log.info("请求住户参数：{}",JSON.toJSONString(residentInfoDTO));
                                List<ResidentEstateRelation> resultJson = residentInfoService.getList(residentInfoDTO);
                                if (!CollectionUtils.isEmpty(resultJson)){
                                    List<Integer> orgIds = resultJson.stream().map(ResidentEstateRelation::getOrganizationId).distinct().collect(Collectors.toList());;
                                    OrganizationQuery query = new OrganizationQuery();
                                    query.setIds(orgIds);
                                    //区域
                                    query.setTypes(Arrays.asList(7));
                                    log.info("请求参数：{}",JSON.toJSONString(query));
                                    Map<Integer,List<Organization>> listMap = accountCentService.getParent(query);
                                    if (!CollectionUtils.isEmpty(listMap)){
                                        listMap.keySet().forEach(id -> {
                                            if (!CollectionUtils.isEmpty(listMap.get(id))){
                                                List<Integer> areaId = listMap.get(id).stream()
                                                        .filter(organization -> Objects.nonNull(organization.getType()) && organization.getType().equals(7))
                                                        .map(Organization::getId).distinct().collect(Collectors.toList());
                                                if (!CollectionUtils.isEmpty(areaId)){
                                                    areaIds.addAll(areaId);
                                                }
                                            }
                                        });
                                    }
                                }
                                if(!CollectionUtils.isEmpty(areaIds)){
                                    List<String> result = new ArrayList<>();
                                    areaIds.forEach(id->{
                                        if (jsonObject.containsKey(String.valueOf(id))){
                                            result.add(jsonObject.getString(String.valueOf(id)));
                                        }
                                    });
                                    return result;
                                }
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("获取社区ID失败：{}",e);
        }
        return communityIds;
    }
    /**
     * 海康云眸获取人员门禁设备信息
     * @param  personId
     * @param  communityId
     * @return
     */
    public HaiKangYunMouJson getAuthDevices(String personId, String communityId, VisitorIntegrationConfigDTO config){
        Map<String, Object> map = new HashMap<>();
        map.put(HaiKangYunMouConstant.PERSON_ID, personId);
        map.put(HaiKangYunMouConstant.COMMUNITY_ID, communityId);
        map.put(HaiKangYunMouConstant.PERSON_TYPE, 1);
        HaiKangYunMouConfig haiKangYunMouConfig = new HaiKangYunMouConfig();
        BeanUtils.copyProperties(config, haiKangYunMouConfig);
        HaiKangYunMouJson resp = doReq(HaiKangYunMouConstant.DEVICE_LIST,
                map, Method.GET, haiKangYunMouConfig, null);
        return resp;
    }
    /**
     * 海康云眸获取完整人行配置
     * @param  projectId
     * @return
     */
    public PedestrianIntegrationConfigDTO getConfig(Integer projectId) {
        String projectIdKey = HaiKangYunMouConstant.CONFIG + projectId;
        PedestrianIntegrationConfigDTO config;
        Object o = redisUtils.get(projectIdKey);
        if (ObjectUtils.isEmpty(o)) {
            setConfig();
            config = (PedestrianIntegrationConfigDTO) redisUtils.get(projectIdKey);
        } else {
            config = (PedestrianIntegrationConfigDTO) o;
        }
        return config;
    }

    public void setConfig() {
        // 获取到需要执行拉取人行出入记录的项目及配置
        List<PedestrianIntegrationConfigDTO> integrationConfigDTOList = integrationConfig.getIntegrationConfig(null)
                .getOrDefault(PedestrianMethodEnum.DEVICE.getId(), Collections.emptyList());
        integrationConfigDTOList.forEach(config -> {
            try {
                String projectIdKey = HaiKangYunMouConstant.CONFIG + config.getProjectId();
                redisUtils.setWithMinute(projectIdKey, config, 15);
            } catch (Exception e) {
                log.error("设置完整人行配置失败：{}", e.toString());
            }
        });
    }

    /**
     * 根据第三方设备id获取设备中台id
     * @param projectId
     * @param productId
     * @param devices
     * key-HaiKangYunMouConstant.DEVICE+海康云眸id
     * value-设备中台id
     */
    public void mapThirdDeviceId(Integer projectId, Integer productId, List<HaiKangYunMouDevice> devices) {
        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setProjectId(projectId);
        devicePageQuery.setProductId(productId);
        devicePageQuery.setDeviceTypeId(CategoryEnum.DOOR.getId());
        List<String> deviceIds = devices.stream().map(HaiKangYunMouDevice::getDeviceId).collect(Collectors.toList());
        devicePageQuery.setThirdDeviceIdList(deviceIds);
        Page<DeviceDTO> devicePage = deviceCentService.pageDevice(null, devicePageQuery);
        log.info("海康云眸查询设备中台数据：{}", JSONObject.toJSONString(devicePage));
        if (!CollectionUtils.isEmpty(devicePage.getRecords())) {
            List<DeviceDTO> records = devicePage.getRecords();
            for (DeviceDTO record : records) {
                String deviceKey = HaiKangYunMouConstant.DEVICE + record.getThirdDeviceId();
                redisUtils.setWithMinute(deviceKey, record.getId(), 15);
            }
        }
    }


    /**
     *
     * @param url 请求路径
     * @param params 请求参数
     * @param reqType @
     * @return
     */
    public HaiKangYunMouJson doReq(String url, Map<String, Object> params,
                                   Method reqType, HaiKangYunMouConfig haiKangYunMouConfig, String contentType) {
        Integer projectId = haiKangYunMouConfig.getProjectId();
        String ak = haiKangYunMouConfig.getAk();
        String sk = haiKangYunMouConfig.getSk();

        String path = HaiKangYunMouConstant.HOST + url;
        String result;
        log.error("HaiKangYunMou获取参数为,params{}",params);
        if (reqType.equals(Method.GET)) {
            result = getReq(path, params, getToken(projectId, ak, sk));
        } else if (reqType.equals(Method.POST)) {
            result = postReq(path, params, getToken(projectId, ak, sk), contentType);
        } else if (reqType.equals(Method.DELETE)) {
            path = path + "/" + params.get(HaiKangYunMouConstant.PERSON_ID);
            log.info("path{}",path);
            result = deleteReq(path, getToken(projectId, ak, sk));
        } else {
            throw new RuntimeException();
        }
        if (StringUtils.isEmpty(result)) {
            log.error("HaiKangYunMou exception, projectId:{}", projectId);
            throw new BusinessException("请求海康云眸数据异常，项目：" + projectId);
        }
        HaiKangYunMouJson resp = JSONObject.parseObject(result, HaiKangYunMouJson.class);
        if (resp.getCode().equals(AUTHENTICATION_FAILED_CODE)) {
            String tokenKey = HaiKangYunMouConstant.TOKEN + projectId;
            redisUtils.remove(tokenKey);
            setToken(projectId, ak, sk);
            doReq(url, params, reqType, haiKangYunMouConfig, contentType);
        }
        if (!SUCCESS_CODE.equals(resp.getCode())) {
            log.error("HaiKangYunMou exception, projectId:{}, msg:{}", projectId, resp.getMessage());
            throw new BusinessException("请求海康云眸数据异常，项目：" + projectId + "，请求路径：" + path + "，响应：" +
                    resp.getCode() + "，异常信息：" + resp.getMessage());
        }
        return resp;
    }



    private String getReq(String path, Map<String, Object> map, String token) {
        String resp;
        try {
            resp = HttpRequest.get(path)
                    .bearerAuth(token)
                    .form(map)
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute()
                    .body();
        } catch (Exception e) {
            log.error("HaiKangYunMou get exception path:{}, token:{}, parm:{}, error:{}",
                    path, token, map.toString(), e.getMessage());
            throw new BusinessException("请求海康云眸数据异常：" + path);
        }
        return resp;
    }

    private String postReq(String path, Map<String, Object> map, String token, String contentType) {
        String resp;
        try {
            if (!StringUtils.isEmpty(contentType)) {
                // 标准模式
                resp = HttpRequest.post(path)
                        .bearerAuth(token)
                        .form(map)
                        .setConnectionTimeout(3000)
                        .setReadTimeout(5000)
                        .execute()
                        .body();


            } else {
                // json
                String parm = new JSONObject(map).toJSONString();
                resp = HttpRequest.post(path)
                        .bearerAuth(token)
                        .body(parm)
                        .setConnectionTimeout(3000)
                        .setReadTimeout(5000)
                        .execute()
                        .body();
            }
        } catch (Exception e) {
            log.error("HaiKangYunMou post exception path:{}, token:{}, parm:{}, error:{}",
                    path, token, map.toString(), e.getMessage());
            throw new BusinessException("请求海康云眸数据异常：" + path);
        }
        return resp;
    }

    private String deleteReq(String path, String token) {
        String resp;
        try {
            resp = HttpRequest.delete(path)
                    .bearerAuth(token)
                    .setConnectionTimeout(3000)
                    .setReadTimeout(5000)
                    .execute()
                    .body();
        } catch (Exception e) {
            log.error("HaiKangYunMou post exception path:{}, token:{}, error:{}",
                    path, token, e.getMessage());
            throw new BusinessException("请求海康云眸数据异常：" + path);
        }
        return resp;
    }

}
